<!-- src/components/MusicView.vue -->
<template>
  <v-app>
    <v-container>
      <v-row>
        <v-col cols="12">
          <v-card>
  <v-card-title>
    音乐管理
    <v-spacer></v-spacer>
    <v-btn color="primary" @click="openDialog()">
      添加音乐
    </v-btn>
  </v-card-title>
  <v-card-text>
    <v-text-field
      v-model="search"
      label="搜索音乐"
      class="mb-4"
      clearable
    ></v-text-field>
    <v-select
        v-model="search_package_id"
        :items="music_packages"
        label="请根据音乐包所有对应的音乐"
        item-title="name"
        item-value="id"
        variant="outlined"
        @update:modelValue="handleSelectChange"
    ></v-select>
    <v-data-table
      :headers="headers"
      :items="musics"
      :loading="loading"
      :search="search"
      class="elevation-1"
    >
      <template v-slot:item.actions="{ item }">
        <v-icon small @click="deleteItem(item)">
          mdi-delete
        </v-icon>
      </template>
    </v-data-table>
  </v-card-text>
</v-card>
        </v-col>
      </v-row>

      <!-- 编辑对话框 -->
      <v-dialog v-model="dialog" max-width="500px">
        <v-card>
          <v-card-title>
            <span>{{ formTitle }}</span>
          </v-card-title>
          <v-card-text>
            <v-container>
              <v-row>
                <v-col cols="12">
                  <v-text-field
                    v-model="editedItem.name"
                    label="音乐名称"
                  ></v-text-field>
                </v-col>
                <v-col cols="12">
                  <v-select
                      v-model="editedItem.package_id"
                      label="请选择音乐包"
                      :items=music_packages
                      item-title="name"
                      item-value="id"
                      variant="outlined"
                  ></v-select>
                </v-col>
                <v-col cols="12">
                  <v-file-input
                    v-model="editedItem.file"
                    label="上传音乐文件"
                    show-size
                    prepend-icon="mdi-upload"
                    accept=""
                  ></v-file-input>
                  <div v-if="editedItem.url" class="mt-2">
                    当前文件:
                    <a :href="editedItem.url" target="_blank">
                      {{ editedItem.url }}
                    </a>
                  </div>
                </v-col>
              </v-row>
            </v-container>
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="blue darken-1" text @click="close">取消</v-btn>
            <v-btn color="blue darken-1" text @click="save">保存</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>

      <!-- 删除确认对话框 -->
      <v-dialog v-model="dialogDelete" max-width="500px">
        <v-card>
          <v-card-title>确认删除</v-card-title>
          <v-card-text>确定要删除这条音乐记录吗？</v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="blue darken-1" text @click="closeDelete">取消</v-btn>
            <v-btn color="blue darken-1" text @click="deleteItemConfirm">确认</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-container>
  </v-app>
</template>

<script>
const API_BASE = import.meta.env.VITE_API_BASE || 'http://106.75.215.61:3000';

export default {
  name: 'MusicView',
  data: () => ({
    apiBase: API_BASE,
    dialog: false,
    dialogDelete: false,
    loading: false,
    search: '', // 搜索关键词
    // ✅ 改为 Vuetify 3 的写法：title + key
    headers: [
      { title: '音乐ID', key: 'id' },
      { title: '音乐名称', key: 'name' },
      { title: '音乐链接', key: 'url' },
      { title: '音乐包名称', key: 'package_name' },
      { title: '操作', key: 'actions', sortable: false }
    ],
    musics: [],
    music_packages: [],
    search_package_id: "全部",
    editedIndex: -1,
    editedItem: {
      id: '',
      name: '',
      url: '',
      package_id: '',
      package_name: '',
      file: null
    },
    defaultItem: {
      id: '',
      name: '',
      url: '',
      package_id: '',
      package_name: '',
      file: null
    }
  }),

  computed: {
    formTitle() {
      return this.editedIndex === -1 ? '新增音乐' : '编辑音乐'
    },
  },

  methods: {
    async getAllMusic() {
      this.loading = true
      try {
        const res = await this.$axios.get(`${this.apiBase}/getAllMusic`)
        this.musics = res.data
      } catch (e) {
        this.$toast?.error('获取音乐列表失败')
      } finally {
        this.loading = false
      }
    },

    async getAllMusicByPackageId(packageId) {
      this.loading = true
      try {
        this.musics.length = 0;
        const res = await this.$axios.get(`${this.apiBase}/getAllMusicByPackageId/` + packageId)
        this.musics = res.data
      } catch (e) {
        this.$toast?.error('获取音乐列表失败')
      } finally {
        this.loading = false
      }
    },

    async getAllMusicPackages() {
      this.loading = true
      try {
        const res = await this.$axios.get(`${this.apiBase}/getAllMusicPackages`)
        this.music_packages = res.data
      } catch (e) {
        this.$toast?.error('获取音乐包列表失败')
      } finally {
        this.loading = false
      }
    },

    async deleteMusic(id) {
      this.loading = true
      try {
        const res = await this.$axios.get(`${this.apiBase}/deleteMusic/` + id)
        if (res.status === 200) {
          this.$toast?.success('删除成功')
        } else {
          throw new Error('删除失败')
        }
      } catch (e) {
        this.$toast?.error('删除失败')
      } finally {
        this.loading = false
      }
    },

    async handleSelectChange(){
      console.log('选中的值:', this.search_package_id);
      await this.getAllMusicByPackageId(this.search_package_id);

      // 在这里执行你的逻辑
    },

    openDialog() {
      this.editedIndex = -1
      this.editedItem = Object.assign({}, this.defaultItem)
      this.dialog = true
    },

    deleteItem(item) {
      this.editedIndex = this.musics.indexOf(item)
      this.editedItem = Object.assign({}, item)
      this.dialogDelete = true
    },

    close() {
      this.dialog = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
      })
    },

    closeDelete() {
      this.dialogDelete = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
      })
    },

    async save() {
      if (!this.editedItem.name || !this.editedItem.file || !this.editedItem.package_id) {
        this.$toast?.error('请填写名称并选择文件')
        return
      }

      if (this.editedIndex > -1) {
        Object.assign(this.musics[this.editedIndex], this.editedItem)
      } else {
        const formData = new FormData()
        formData.append('name', this.editedItem.name)
        formData.append('musicFile', this.editedItem.file)
        formData.append('package_id', this.editedItem.package_id)
        this.loading = true
        try {
          const response = await this.$axios.post(`${this.apiBase}/addMusic`, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          })

          if (response.status !== 200) throw new Error('上传失败')

          const { id, name, url } = response.data.data

          // 从package数组中获取package_id对应的name
          console.log(this.music_packages)
          const package_obj = this.music_packages.find(pkg => pkg.id === this.editedItem.package_id);
          console.log(package_obj)
          const package_name = package_obj ? package_obj.name : '未知包';

          Object.assign(this.editedItem, { id, name, url, package_name })
          this.$toast?.success('上传成功')

          this.musics.push({ ...this.editedItem })
          this.close()
        } catch (e) {
          this.$toast?.error('上传失败')
        } finally {
          this.loading = false
        }
      }

      this.close()
    },

    async deleteItemConfirm() {
      await this.deleteMusic(this.editedItem.id)
      this.musics.splice(this.editedIndex, 1)
      this.closeDelete()
    }
  },

  mounted() {
    this.getAllMusic()
    this.getAllMusicPackages()
  }
}
</script>
